﻿using _18自引用的组织结构树.EntityClass;
using Microsoft.EntityFrameworkCore;

namespace _18自引用的组织结构树;

class Program
{
    static async Task Main(string[] args)
    {
        using MyDbContext ctx = new MyDbContext();
        /*OrgUnit root = new OrgUnit() { Name = "root" };
        
        OrgUnit middle1 = new OrgUnit() { Name = "middle1" };
        OrgUnit middle2 = new OrgUnit() { Name = "middle2" };

        OrgUnit child1_1 = new(){Name = "child1_1"};
        OrgUnit child1_2 = new(){Name = "child1_2"};
        
        OrgUnit child2_1 = new(){Name = "child2_1"};
        OrgUnit child2_2 = new(){Name = "child2_2"};
        
        root.Children.AddRange([middle1,middle2]);
        middle1.Children.AddRange([child1_1,child1_2]);
        middle2.Children.AddRange([child2_1,child2_2]);
        
        ctx.OrgUnits.Add(root);
        await ctx.SaveChangesAsync();*/
        
        /*
        OrgUnit child1_1_1 = new() { Name = "child1_1_1" };
        OrgUnit child1_1_2 = new() { Name = "child1_1_2" };
        OrgUnit child1_1_3 = new() { Name = "child1_1_3" };
        ctx.OrgUnits.Single(o=>o.ID==6).Children.AddRange([child1_1_1,child1_1_2,child1_1_3]);
        await ctx.SaveChangesAsync();
        
        var root = ctx.OrgUnits.Single(o => o.Name == "root");
        Console.WriteLine(root.Name);
        PrintUnit(1,ctx,root);*/

        // Teacher teacher1 = new() { Name = "teacher1" };
        // Teacher teacher2 = new() { Name = "Teacher2" };
        // Teacher teacher3 = new() { Name = "Teacher3" };
        //
        // Student student1 = new() {Name = "学生1"};
        // Student student2 = new() {Name = "学生2"};
        // Student student3 = new() {Name = "学生3"};
        //
        // teacher1.Students.AddRange([student1,student2]);
        // teacher2.Students.AddRange([student1,student3]);
        // teacher3.Students.AddRange([student2,student3]);
        //
        // ctx.Teachers.AddRange([teacher1,teacher2,teacher3]);
        //ctx.Students.
        // await ctx.SaveChangesAsync();
        var teachers = await ctx.Teachers.Include(t => t.Students).ToListAsync();
        foreach (var teacher in teachers )
        {
            Console.WriteLine($"ID:{teacher.Id}|name:{teacher.Name}");
            foreach (var student in teacher.Students)
            {
                Console.WriteLine(new string('\t',1)+$"ID:{student.Id}|name:{student.Name}");
            }
        }
    }

    static void PrintUnit(int count, MyDbContext ctx, OrgUnit parent)
    {
        var result = ctx.OrgUnits.Where(o => o.Parent == parent);
        foreach (var orgUnit in result)
        {
            Console.WriteLine(new string('\t',count)+orgUnit.Name);
            PrintUnit(count+1,ctx,orgUnit);
        }
    }
}